package com.danhuang.cloud.danhuanggateway.Interceptor;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.danhuang.cloud.danhuangcore.constant.ResConstant;
import com.danhuang.cloud.danhuangcore.model.DhRes;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

public class OpenIdFInterceptor implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        if( !"/daily/photo/photo/down".equals(exchange.getRequest().getURI().getPath())){

            String openId = Optional.ofNullable(exchange.getRequest().getHeaders().get("openId"))
                    .orElse(new ArrayList<>()).stream()
                    .findFirst().orElse(null);

            if(StrUtil.isBlank(openId)){
                return Mono.defer(()-> {
                    ServerHttpResponse response = exchange.getResponse();

                    return response.writeWith(Mono.just(response.bufferFactory()
                            .wrap(JSONUtil.toJsonStr(DhRes.fail(ResConstant.NO_OPENID_CODE))
                                    .getBytes(StandardCharsets.UTF_8))));
                });
            }
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
